// 评分分布柱状图API数据格式要求：
// [
//   { rating: '9.7', count: 1 },
//   { rating: '9.6', count: 2 },
//   ...
// ]
// 如果API可用则优先显示API数据，否则显示默认数据

document.addEventListener('DOMContentLoaded', function() {
    // 获取容器
    const chartDom = document.getElementById('ratingBar');
    const chart = echarts.init(chartDom);
    
    // 显示加载动画
    chart.showLoading({
        text: '数据加载中...',
        color: '#14c8fd',
        textColor: '#fff',
        maskColor: 'rgba(13, 26, 45, 0.8)'
    });

    // 默认数据
    let data = [
        { rating: '9.7', count: 1 },
        { rating: '9.6', count: 2 },
        { rating: '9.5', count: 5 },
        { rating: '9.4', count: 8 },
        { rating: '9.3', count: 12 },
        { rating: '9.2', count: 15 },
        { rating: '9.1', count: 20 },
        { rating: '9.0', count: 25 },
        { rating: '8.9', count: 30 },
        { rating: '8.8', count: 35 }
    ].sort((a, b) => b.rating - a.rating);

    // API接口地址（如有则优先使用API数据）
    const apiUrl = '/api/rating/distribution';

    // 尝试从API获取数据
    fetch(apiUrl)
        .then(res => {
            if (!res.ok) throw new Error('Network response was not ok');
            return res.json();
        })
        .then(response => {
            // 检查返回的数据格式是否正确
            if (response.code === 200 && response.data) {
                // 将对象格式转换为数组格式
                data = Object.entries(response.data).map(([rating, count]) => ({
                    rating: rating,
                    count: count
                })).sort((a, b) => b.rating - a.rating);
                console.log('成功获取评分分布数据：', data);
            }
        })
        .catch(err => {
            console.warn('使用默认数据，API获取失败：', err);
        })
        .finally(() => {
            renderChart(data);
        });

    // 渲染图表的函数
    function renderChart(data) {
        // 图表配置项
        const option = {
            backgroundColor: 'transparent',
            title: {
                text: '电影评分分布',
                left: 'center',
                top: 20,
                textStyle: {
                    color: '#fff',
                    fontSize: '16'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                backgroundColor: 'rgba(13, 26, 45, 0.8)',
                borderColor: '#14c8fd',
                textStyle: {
                    color: '#fff'
                },
                formatter: function(params) {
                    return `评分：${params[0].name}<br/>电影数量：${params[0].value}部`;
                }
            },
            grid: {
                top: '15%',
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: data.map(item => item.rating),
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 12,
                    interval: 0
                }
            },
            yAxis: {
                type: 'value',
                name: '电影数量',
                nameTextStyle: {
                    color: '#fff'
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 12
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                }
            },
            series: [{
                name: '电影数量',
                type: 'bar',
                data: data.map(item => item.count),
                barWidth: '60%',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: '#14c8fd'
                    }, {
                        offset: 1,
                        color: '#43eec6'
                    }]),
                    borderRadius: [8, 8, 0, 0]
                },
                emphasis: {
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: '#43eec6'
                        }, {
                            offset: 1,
                            color: '#14c8fd'
                        }])
                    }
                },
                animationDelay: function(idx) {
                    return idx * 100;
                },
                animationDelayUpdate: function(idx) {
                    return idx * 100;
                }
            }]
        };

        // 使用配置项显示图表
        chart.hideLoading();
        chart.setOption(option);

        // 添加动画效果
        let currentIndex = -1;
        const dataLen = data.length;
        const highlight = () => {
            // 取消之前的高亮
            if (currentIndex >= 0) {
                chart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    dataIndex: currentIndex
                });
            }
            currentIndex = (currentIndex + 1) % dataLen;
            // 高亮当前柱子
            chart.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: currentIndex
            });
            // 显示tooltip
            chart.dispatchAction({
                type: 'showTip',
                seriesIndex: 0,
                dataIndex: currentIndex
            });
        };

        // 开启定时器
        let timeId = setInterval(highlight, 2000);

        // 鼠标移入停止自动高亮
        chart.on('mouseover', function(params) {
            clearInterval(timeId);
            chart.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: params.dataIndex
            });
        });

        // 鼠标移出恢复自动高亮
        chart.on('mouseout', function(params) {
            chart.dispatchAction({
                type: 'downplay',
                seriesIndex: 0,
                dataIndex: params.dataIndex
            });
            timeId = setInterval(highlight, 2000);
        });

        // 添加渐变动画
        function updateGradient() {
            const colors = [
                ['#14c8fd', '#43eec6'],
                ['#43eec6', '#14c8fd'],
                ['#14c8fd', '#ff69b4'],
                ['#ff69b4', '#14c8fd']
            ];
            let colorIndex = 0;

            setInterval(() => {
                const newColor = colors[colorIndex];
                option.series[0].itemStyle.color = new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: newColor[0]
                }, {
                    offset: 1,
                    color: newColor[1]
                }]);
                chart.setOption(option);
                colorIndex = (colorIndex + 1) % colors.length;
            }, 3000);
        }

        updateGradient();

        // 监听窗口大小变化
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
}); 